package com.example.app.page;

import android.app.AlertDialog;
import android.app.Application;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Patterns;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.app.R;
import com.example.app.api.LoginService;
import com.example.app.config.RetrofitClient;
import com.example.app.entity.RegisterRequest;
import com.example.app.entity.RegisterResponse;

import java.io.IOException;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class RegisterActivity extends AppCompatActivity {
    private EditText etUsername, etPassword, etEmail;
    private Button btnRegister, backLoginButton;
    private ProgressDialog progressDialog;

    private RetrofitClient retrofitClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        retrofitClient = RetrofitClient.getInstance((Application) getApplicationContext());

        setContentView(R.layout.register);

        etUsername = findViewById(R.id.et_username);
        etPassword = findViewById(R.id.et_password);
        etEmail = findViewById(R.id.et_email);
        btnRegister = findViewById(R.id.btn_register);
        backLoginButton = findViewById(R.id.backLoginButton);

        btnRegister.setOnClickListener(v -> attemptRegister());

        backLoginButton.setOnClickListener(v -> {
            // 跳转到注册界面
            Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
            startActivity(intent);
            finish();
        });
    }

    private void attemptRegister() {
        String username = etUsername.getText().toString().trim();
        String password = etPassword.getText().toString().trim();
        String email = etEmail.getText().toString().trim();

        // 本地校验
        if (TextUtils.isEmpty(username)) {
            showError("用户名不能为空");
            return;
        }
        if (TextUtils.isEmpty(password) || password.length() < 6) {
            showError("密码至少需要6位");
            return;
        }
        if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
            showError("邮箱格式不正确");
            return;
        }

        showProgress();
        RegisterRequest request = new RegisterRequest(username, password, email);

        LoginService register = retrofitClient.getLoginService(LoginService.class);
        Call<ResponseBody> call = register.register(request);

        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                dismissProgress();
                try {
                    String responseBody = response.body() != null ? response.body().string() : "";
                    if (response.isSuccessful()) {
                        if ("注册成功".equals(responseBody)) {
                            handleRegisterResult(new RegisterResponse(true, "注册成功"));
                            Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
                            startActivity(intent);
                            finish();
                        } else {
                            showError("未知响应: " + responseBody);
                        }
                    } else {
                        // 处理错误信息（如：400返回"用户名已被注册"）
                        handleRegisterResult(new RegisterResponse(false, responseBody));
                    }
                } catch (IOException e) {
                    showError("响应解析失败");
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                dismissProgress();
                showError("网络错误: " + t.getMessage());
            }
        });
    }

    private void handleRegisterResult(RegisterResponse response) {
        if (response.isSuccess()) {
            Toast.makeText(this, "注册成功", Toast.LENGTH_SHORT).show();
            finish(); // 返回登录界面
        } else {
            showError(response.getMessage());
        }
    }

    private void showProgress() {
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("注册中...");
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    private void dismissProgress() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    private void showError(String message) {
        new AlertDialog.Builder(this)
                .setTitle("提示")
                .setMessage(message)
                .setPositiveButton("确定", null)
                .show();
    }
}